package labeler;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class LabeledCollection<TValue, TLabel> {
	
	private Map<TLabel, Set<TValue>> labelsToValues = new HashMap<>();
	private Map<TValue, Set<TLabel>> valuesToLabels = new HashMap<>();
	
	@SafeVarargs
	public final void add(TValue value, TLabel... labels) {
		addValueToLabels(value, labels);
		addLabelsToValue(value, labels);
	}

	@SafeVarargs
	private final void addValueToLabels(TValue value, TLabel... labels) {
		for (TLabel label : labels) {
			Set<TValue> values = labelsToValues.get(label);
			if (values == null) {
				values = new HashSet<TValue>();
				labelsToValues.put(label, values);
			}
			values.add(value);
		}
	}

	@SafeVarargs
	private final void addLabelsToValue(TValue value, TLabel... labels) {
		Set<TLabel> currentLabels = valuesToLabels.get(value);
		if (currentLabels == null) {
			currentLabels = new HashSet<TLabel>();
			valuesToLabels.put(value, currentLabels);
		}
		
		currentLabels.addAll(Arrays.asList(labels));
	}
	
	public HashSet<TValue> getValuesFor(TLabel label) {
		if (labelsToValues.containsKey(label)) {
			return new HashSet<TValue>(labelsToValues.get(label));
		} else {
			return new HashSet<TValue>();
		}
	}

	public HashSet<TLabel> getLabelsFor(String value) {
		if (valuesToLabels.containsKey(value)) {
			return new HashSet<TLabel>(valuesToLabels.get(value));
		} else {
			return new HashSet<TLabel>();
		}
	}
}
